package com.btr.ivle.backgroud;

import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;


import android.content.Context;
import android.os.AsyncTask;

import com.btr.ivle.R;
import com.btr.ivle.data.IVLEToken;
import com.btr.ivle.helper.URLtoString;

public class GetEventDetailTask extends AsyncTask<String, Void, Map<String, String>>{
	
	private Context context;
	
	public GetEventDetailTask(Context context){
		this.context = context;
	}

	protected Map<String, String> doInBackground(String... strings) {
		Map<String, String> map = new HashMap<String, String>();
		String title = strings[0];
		
		try{
        	URL url = new URL("https://ivle.nus.edu.sg/api/Lapi.svc/StudentEvents?APIKey=" +
        			context.getString(R.string.IVLE_API_KEY) + "&AuthToken=" + IVLEToken.getToken() + "&TitleOnly=false");
        	
        	JSONObject jObject = new JSONObject(URLtoString.get(url));
	        JSONArray resultsArrary = jObject.getJSONArray("Results");
	        
	        for (int i = 0; i < resultsArrary.length(); i++) {
	        	if(title.equals(resultsArrary.getJSONObject(i).getString("Title").toString())){
	        		map.put("Title", title);
	        		map.put("Description", resultsArrary.getJSONObject(i).getString("Description").toString());
	        		map.put("Organizer", resultsArrary.getJSONObject(i).getString("Organizer").toString());
	        		map.put("EventDateTime", resultsArrary.getJSONObject(i).getString("EventDateTime").toString());
	        		map.put("Venue", resultsArrary.getJSONObject(i).getString("Venue").toString());
	        		map.put("Price", resultsArrary.getJSONObject(i).getString("Price").toString());
	        		map.put("Agenda", resultsArrary.getJSONObject(i).getString("Agenda").toString());
	        		map.put("Contact", resultsArrary.getJSONObject(i).getString("Contact").toString());
	        	}
			}
        }catch(Exception ex){
	    }
		return map;
	}
	
    @SuppressWarnings("unchecked")
	protected void onPostExecute(Map<String, String> map) {
    	AsyncTaskCompleteListener<String> l = (AsyncTaskCompleteListener<String>) context;
    	l.onAsyncTaskComplete("");
    }
}
